<template>
    <div class="container">
        <div id="btn-box">
            <input type="checkbox" class="btn-check" id="btn-check-outlined" v-model="next_week" autocomplete="off">
            <label class="btn btn-light btn-lg text-nowrap bi" for="btn-check-outlined"><span
                    :class="next_week ? 'bi-arrow-left-circle' : 'bi-arrow-right-circle'"></span>&nbsp;{{ next_week ?
                        '返回这' : '进入下' }}一周</label>

            <button type="button" class="btn btn-light btn-lg text-nowrap" @click="edit_dg"><span
                    class="bi bi-pencil-square"></span>&nbsp;每日配菜</button>
            <button type="button" class="btn btn-light btn-lg text-nowrap" @click="edit_jing"><span
                    class="bi bi-pencil-square"></span>&nbsp;每日灵奶</button>
            <button type="button" class="btn btn-light btn-lg text-nowrap" @click="add_footer"><span
                    class="bi bi-pen"></span>&nbsp;脚注</button>
            <button type="button" class="btn btn-light btn-lg text-nowrap" @click="if_save"><span
                    class="bi bi-download"></span>&nbsp;打包下载</button>
            <button type="button" class="btn btn-light btn-lg text-nowrap" @click="if_clear"><span
                    class="bi bi-trash"></span>&nbsp;清空数据</button>
        </div>
        <div class="row justify-content-md-center" id='show_cards'>

            <div class="col-md-4 col-sm-12" v-for="(i, index) of data">
                <div class="card text-bg-light my-3 text-center" ref="cards"
                    @mouseenter="$event.target.children[1].children[2].style['z-index'] = 2"
                    @mouseleave="$event.target.children[1].children[2].style['z-index'] = -2">

                    <h1 class="card-header">
                        {{ i[0] }}
                    </h1>
                    <div class="card-body">
                        <div class="card-title"><strong>☀️ 心满意足餐厅 ☀️</strong></div>

                        <div class="card-text text-start">
                            <span class="text-secondary">🍼每日灵奶:</span><br>

                            <div style="white-space: pre-wrap;">{{ chajing_computed }}
                            </div>
                            <br>
                            <span class="text-secondary">🍱每日配菜:</span><br>
                            <div class="dg-item" v-for="dg of i[1]">🌿{{ dg }}</div>
                            <br>
                            <span class="text-secondary">🥞营养丰富，均衡搭配🍷</span><br>
                        </div>
                        <button name="btn-copy" type="button" class="btn btn-sm btn-secondary" ref="btns"
                            @click="copy_as_img(index, $event)">复制为图片</button>
                    </div>
                    <div v-if="card_footer" class="card-footer text-body-secondary text-end fs-6 fst-italic"
                        style="white-space: pre-wrap;">
                        {{ footer_computed }}
                    </div>

                    <!-- <img :style="img_style" name='card_img' :src='i[2]' /> -->
                </div>
            </div>
        </div>
    </div>


    <ShowModal :title="currentComponent.modal_title" ref="modal_ref" :action_btns="currentComponent.modal_actions"
        :size="currentComponent.size">
        <template #body>
            <component :is="currentComponent.component" v-on="currentComponent.event" v-bind="currentComponent.bind">
            </component>
            <!-- <YuForm @submitForm="handle_msg"></YuForm> -->
        </template>
        <template #footer>
            <component :is="currentComponent.footer_component" v-on="currentComponent.footer_event"
                v-bind="currentComponent.footer_bind"></component>
        </template>
    </ShowModal>

</template>

<script setup>
import { ref, shallowRef, useTemplateRef, watch, onMounted, computed } from 'vue'
import html2canvas from 'html2canvas'
import ShowModal from './ShowModal.vue'
import { get_data } from '@/assets/processing_data'
import JSZip from 'jszip'

const cardRefs = useTemplateRef('cards')
const btnRefs = useTemplateRef('btns')
const modal_ref = useTemplateRef('modal_ref')
const next_week = ref(false)
let msg = ''
let downloading = false
const chajing = ref('完成一页查经作业')
const card_footer = ref('')
const currentComponent = shallowRef({})

const storage = localStorage

// const { cards_data } = defineProps(['cards_data',])
// const img_style = ref({ 'z-index': -1, display: 'none' })

const data = ref([['00月00日 · 周〇', ['示例1', '示例2'], ''],])
let zip_name = ''

onMounted(() => {

    const local_chajing = storage.getItem('chajing')
    if (local_chajing) {
        chajing.value = local_chajing
    }
    const local_msg = storage.getItem('msg')
    if (local_msg) {
        msg = local_msg
        const local_next_week = storage.getItem('next_week')
        if (local_next_week) {
            next_week.value = local_next_week === 'true' ? true : false
        }
        const dg_data = get_data({ msg, is_this_week: !next_week.value })
        if (!dg_data.length) data.value = [['00月00日 · 周〇', ['示例1', '示例2'], ''],]
        else data.value = dg_data
    }
    const local_footer = storage.getItem('footer')
    if (local_footer) {
        card_footer.value = local_footer
    }
})

const footer_computed = computed(() => {
    // 原string已经trim过了
    return card_footer.value.split('\n').reduce((acc, curr) => {
        let line = curr.trim()
        if (line) {
            acc.push(line)
        }
        return acc
    }, []).join('\n')
})

const chajing_computed = computed(() => {
    // return chajing.value.split('\n').map(line => line.trim()).filter(line => line).map(line => "🍇" + line).join('\n')
    return chajing.value.split('\n').reduce((acc, curr) => {
        let line = curr.trim()
        if (line) {
            acc.push("🍇" + line)
        }
        return acc
    }, []).join('\n')
})
const add_footer = () => {
    currentComponent.value = {
        modal_title: '请添加脚注',
        size: "modal-sm",
        component: 'textarea',
        bind: {
            class: "form-control",
            placeholder: '请在此处输入...',
            value: card_footer.value,
            maxlength: "80",
            rows: "4",
        },
        event: {
            input(event) {
                card_footer.value = event.target.value.trim()
                storage.setItem('footer', card_footer.value)
            }
        },
        modal_actions: ['close'],

    }
    modal_ref.value.launch_modal()

}
const edit_dg = () => {
    currentComponent.value = {
        modal_title: '请填写祷告事项',
        component: 'textarea',
        bind: {
            class: "form-control",
            placeholder: "请在此处输入...",
            value: msg,
            maxlength: "800",
            minlength: "4",
            rows: "15",
        },
        event: {
            input(event) {
                msg = event.target.value
            }
        },
        modal_actions: ['close'],
        footer_component: {
            template: `<button type="button" class="btn btn-primary">确定</button>`
        },
        footer_event: {
            click: handle_msg
        }
    }
    modal_ref.value.launch_modal()
}


const edit_jing = () => {
    currentComponent.value = {
        modal_title: '请填入读经事项',
        size: "modal-sm",
        component: 'textarea',
        bind: {
            class: "form-control",
            placeholder: "请在此处输入...",
            value: chajing.value,
            maxlength: "80",
            rows: "4",

        },
        event: {
            input(event) {
                chajing.value = event.target.value.trim()
                storage.setItem('chajing', chajing.value)
            }
        },
        modal_actions: ['close'],
        // footer_component: {
        //     template: `<button type="button" class="btn btn-primary">确定</button>`
        // },
        // footer_event: {
        //     click() {
        //         storage.setItem('chajing', _temp_chajing_.trim())
        //         chajing.value = parse_chajing(_temp_chajing_)
        //         modal_ref.value.hide_modal()
        //     }
        // }
    }
    modal_ref.value.launch_modal()
}
const handle_msg = () => {
    storage.setItem(
        'next_week', next_week.value)
    if (!msg) {
        data.value = [['00月00日 · 周〇', ['示例1', '示例2'], ''],]
    }
    else {
        storage.setItem('msg', msg.trim())
        const dg_data = get_data({ msg, is_this_week: !next_week.value })
        if (!dg_data.length) data.value = [['00月00日 · 周〇', ['示例1', '示例2'], ''],]
        else data.value = dg_data
    }
    modal_ref.value.hide_modal()
}
watch(next_week, () => handle_msg())

const get_canvas = async to_render => {

    return html2canvas(to_render, {
        scale: 2.5,
        ignoreElements: e => e.tagName === 'BUTTON',
        onclone: (doc, e) => {
            e.style['border-style'] = 'none'
        },
    })
}
const copy_blob = async blob => {
    const img_item = new window.ClipboardItem({ 'image/png': blob })
    await navigator.clipboard.write([img_item])
}

const copy_as_img = async (index, event) => {
    // index可以方便地从data中获取数据后复制文字
    const btn_ref = event.target

    if (btn_ref.classList.contains('disabled')) return
    // 所有按钮为恢复可点击
    // await Promise.allSettled(btnRefs.value.map(btn => btn.classList.toggle('disabled', false)))
    btnRefs.value.forEach(btn => {
        btn.classList.toggle('disabled', false)
        btn.innerHTML = '复制为图片'
    })
    btn_ref.classList.toggle('disabled', true)
    btn_ref.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>`
    try {
        const a_canvas = await get_canvas(btn_ref.parentNode.parentNode)
        a_canvas.toBlob(copy_blob)
        // throw Error('something was wrong!')
        btn_ref.innerHTML = '复制完成'
    } catch (e) {
        console.error('Failed to copy: ', e)
        currentComponent.value = {
            component: {
                template: `<div style="font-size:1.1rem">
                    <p>复制图片失败</p>
                    <p>可能是浏览器兼容性问题</p>
                    <p>${e}</p></div>`
            },
            modal_title: '出错了',
            modal_actions: ['close'],
        }
        modal_ref.value.launch_modal()
    }

}

const if_clear = () => {
    currentComponent.value = {
        size: "modal-sm",
        component: {
            template: `<div style="font-size:1.1rem">是否<span class="fw-bold text-danger">删除</span>已输入的内容?</div>`
        },
        modal_title: '请确认',
        modal_actions: ['close'],
        footer_component: {
            template: `<button type="button" class="btn btn-danger">删除</button>`
        },
        footer_event: {
            click: storage_clear
        }
    }
    modal_ref.value.launch_modal()
}
const if_save = () => {
    zip_name = data.value.at(0).at(0).slice(0, 6) + '_' + data.value.at(-1).at(0).slice(0, 6) + '_功课分享.zip'
    const arrow_down = '<span class="bi bi-arrow-down-circle"></span>'.repeat(3)
    currentComponent.value = {
        component: {
            template: `<div style="font-size:1.1rem">
                <p>已将所有图片打包为zip压缩文档</p>
            <p>文件名: <strong>${zip_name}</strong></p>
            <p>请点击下方按钮下载</p>
            </div>`
        },
        modal_title: '请确认',
        modal_actions: ['close'],
        footer_component: {
            template: `<button type="button" class="btn btn-primary">下载</button>`
        },
        footer_event: {
            click: save_all_cards
        }
    }
    modal_ref.value.launch_modal()
}

const save_all_cards = async () => {
    if (downloading) return
    downloading = true
    try {
        const zip = new JSZip()

        for (let card of cardRefs.value) {
            let a_canvas = await get_canvas(card)

            let date_text = card.querySelector('.card-header').innerText

            // canvas的toBlob方法与async有兼容问题
            // 于是使用base64, 小图片还行, 大一点的文件就不行了
            let data = a_canvas.toDataURL('image/jpeg').replace(`data:image/jpeg;base64,`, '')
            zip.file(date_text.replace(' · ', '-') + '.jpg', data, { base64: true })
        }

        const content = await zip.generateAsync({ type: 'blob' })

        let url = URL.createObjectURL(content)
        let a = document.createElement('a')

        a.href = url
        a.download = zip_name

        a.click()
        URL.revokeObjectURL(url)
        modal_ref.value.hide_modal()
        downloading = false
    } catch (e) {
        console.log('错误: ', e)
    }
}
const storage_clear = () => {
    storage.clear()
    location.reload()
}

</script>

<style scoped>
#btn-box {
    /* class="d-inline-flex gap-2 mt-3" */
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: 1rem;
}

div.card-body {
    font-size: 17px;
    font-family: "Microsoft YaHei";
    letter-spacing: 1px;
    line-height: 1.6;
}

div.jingwen-item,
div.dg-item {
    text-indent: -1.29em;
    margin-left: 1.29em;
}


div.card {
    position: relative;
    max-width: 25rem;
    min-width: 21rem;
    /* min-height: 28rem; */
}

div.card-body {
    position: relative;
}

button[name=btn-copy] {
    position: absolute;
    z-index: -2;
    bottom: 0.2rem;
    right: 0.2rem;
    /* transform: translate(-50%, -50%); */
}

img[name=card_img] {
    width: 100%;
    height: 100%;
    object-fit: fill;
    position: absolute;
}

img.img-fluid:hover {
    cursor: pointer;
}

li.page-item.disabled:hover {
    cursor: not-allowed;
}
</style>